package com.zxl.openapi.fallback;


import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 这个fallback只能是在特定情况下才会发生,被代理的服务由正常转为非正常的时候才会触发,如果服务在eureka中找到不到了,则zuul不会触发这个fallback,而是直接抛出异常404,所以这个东西其实没有什么用处
 * 我们主要是靠errorcontroller来去返回指定数据
 */
@Component
public class ZuulFallBackProvider implements FallbackProvider {


    @Override
    public String getRoute() {
        return "*";
    }

    /**
     * 调用服务出现异常
     * @param route 那个服务出现异常了
     * @param cause 出现了什么异常
     * @return
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {

        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.toString();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {

                ByteArrayInputStream bis = new ByteArrayInputStream("在有生的瞬间能遇到你，竟花光所有运气，到今日才发现，曾呼吸过空气".getBytes());

                return bis;

            }

            @Override
            public HttpHeaders getHeaders() {
                return null;
            }

        };
    }
}
